package com.training.admin.web.controller.project;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.persistence.support.QueryFilter;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.utils.WebUtils;
import com.training.admin.entity.project.Project;
import com.training.admin.entity.project.ProjectPhase;
import com.training.admin.entity.project.ProjectPhaseCourse;
import com.training.admin.entity.project.ProjectTrainee;
import com.training.admin.entity.project.TrainingResult;
import com.training.admin.entity.project.TrainingSurvey;
import com.training.admin.entity.search.ProjectDataSearch;
import com.training.admin.entity.security.Login;
import com.training.admin.entity.trainee.Trainee;
import com.training.admin.service.ProjectDataService;
import com.training.admin.service.ProjectPhaseCourseService;
import com.training.admin.service.ProjectPhaseService;
import com.training.admin.service.ProjectTraineeService;
import com.training.admin.service.TraineeService;
import com.training.admin.service.TrainingResultService;
import com.training.admin.service.TrainingSurveyResultService;
import com.training.admin.service.TrainingSurveyService;
import com.training.admin.web.controller.view.ExcelTemplateView;
import com.training.admin.web.resolver.Secure;

/**
 * 
 * @author Rockett
 * 
 */
@Controller
@RequestMapping("/project-results")
@MenuSetting("menu-training-project")
public class ProjectResultController {
    
    private static final Logger logger = LoggerFactory.getLogger(ProjectResultController.class);

	@Autowired
	private ProjectDataService projectDataService;
	
	@Autowired
	private ProjectPhaseService projectPhaseService;
	
	@Autowired
	private TrainingResultService trainingResultService;
	
	@Autowired
	private ProjectPhaseCourseService projectPhaseCourseService;
	
	@Autowired
	private ProjectTraineeService projectTraineeService;
	
	@Autowired
	private TrainingSurveyResultService trainingSurveyResultService;

	@Autowired
	private TrainingSurveyService trainingSurveyService;
	
	@Autowired
	private TraineeService traineeService;

	/**
	 * 项目列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.GET)
	@MenuSetting("submenu-project-result-management")
	public ModelAndView listProjectData(@Secure Login login, Page page, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("project-result/project-result-list");
		int totals = projectDataService.count(login.getDepartmentId());

		if (totals > 0) {

			List<Project> projects = projectDataService.list(login.getDepartmentId(), page.with(totals));

			Map<Long, String> surveyStatusMap = new HashMap<Long, String>();
			Map<Long, String> resultStatusMap = new HashMap<Long, String>();
			
			
			// FIXME
			for (Project project : projects) {

				int surveyCount = trainingSurveyService.count(TrainingSurvey.class,
						new QueryFilter().addEquals("projectPhase.project.id", project.getId()));
				if (surveyCount == 0) {
					surveyStatusMap.put(project.getId(), "未发送");
				} else {
					int surveyResultCount = trainingSurveyResultService.countByProject(project.getId());
					if (surveyResultCount > 0) {
						surveyStatusMap.put(project.getId(), "已评估");
					} else {
						surveyStatusMap.put(project.getId(), "评估中");
					}
				}
				int resultCount = trainingResultService.countByProject(project.getId());
				if (resultCount > 0) {
					resultStatusMap.put(project.getId(), "已录入");
				} else {
					resultStatusMap.put(project.getId(), "未录入");
				}
			}

			modelAndView.addObject("surveyStatusMap", surveyStatusMap);
			modelAndView.addObject("resultStatusMap", resultStatusMap);
			modelAndView.addObject("page", page);
			modelAndView.addObject("projects", projects);
			modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "filter", "page"));

		}

		return modelAndView;
	}

	/**
	 * 查询
	 * 
	 * @return
	 */
	@RequestMapping(value = "/search", method = RequestMethod.GET)
	@MenuSetting("submenu-project-result-management")
	public ModelAndView search(@Secure Login login) {
		ModelAndView modelAndView = new ModelAndView("project-result/project-result-search");
		return modelAndView;
	}

	/**
	 * onSearch
	 * 
	 * @param projectSearch
	 * @param page
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
	@MenuSetting("submenu-project-result-management")
	public ModelAndView onSearch(@Secure Login login, ProjectDataSearch projectDataSearch, Page page,
			HttpServletRequest request) {

		ModelAndView modelAndView = new ModelAndView("project-result/project-result-list");


		int totals = projectDataService.count(login.getDepartmentId(), projectDataSearch);

		if (totals > 0) {

			List<Project> projectList = projectDataService.onSearch(login.getDepartmentId(), projectDataSearch,
					page.with(totals));

			Map<Long, String> surveyStatusMap = new HashMap<Long, String>();
			Map<Long, String> resultStatusMap = new HashMap<Long, String>();
			
			
			// FIXME
			for (Project project : projectList) {

				int surveyCount = trainingSurveyResultService.countByProject(project.getId());

				if (surveyCount > 0) {

					surveyStatusMap.put(project.getId(), "已评估");
				}

				int resultCount = trainingResultService.countByProject(project.getId());

				if (resultCount > 0) {

					resultStatusMap.put(project.getId(), "已录入");
				}
			}

			modelAndView.addObject("surveyStatusMap", surveyStatusMap);
			modelAndView.addObject("resultStatusMap", resultStatusMap);
			modelAndView.addObject("projects", projectList);
			modelAndView.addObject("page", page);
			modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));

		}

		return modelAndView;

	}

    
    /**
     * 成绩录入
     * 
     * @return
     */
    @RequestMapping(value = "/{projectId}/trainee-score-upload", method = RequestMethod.GET)
    public ModelAndView upload(@PathVariable("projectId") Long projectId,
                               @RequestParam Long projectPhaseId) {
        ModelAndView modelAndView = new ModelAndView("project-result/project-trainee-score-upload");
        
        modelAndView.addObject("projectId", projectId);
        modelAndView.addObject("projectPhaseId", projectPhaseId);
        
        return modelAndView;
    }

    /**
     * 批量导入成绩
     * 
     * @return
     */
    @RequestMapping(value = "/{projectId}/trainee-score-upload", method = RequestMethod.POST)
    public ModelAndView onUpload(@PathVariable("projectId") Long projectId,
                                 @RequestParam Long projectPhaseId,
                                 @RequestParam("file") MultipartFile file,
                                 RedirectAttributes attributes) {
        
        try {
            ModelAndView modelAndView = new ModelAndView("redirect:/project-results/" + projectId);

            Project project = projectDataService.load(Project.class, projectId);
            projectTraineeService.updateProjectTraineeByFile(file, project, projectPhaseId);

            return modelAndView;
        } catch (BusinessException e) {
            logger.error("onScoreUpload error", e);
            ModelAndView modelAndView = new ModelAndView("redirect:/project-results/" + projectId + "?scoreMessage="+e.getMessage());
            return modelAndView;
        } catch (Exception e) {
            logger.error("onScoreUpload error", e);
            ModelAndView modelAndView = new ModelAndView("redirect:/project-results/" + projectId + "?scoreMessage=成绩录入发生异常");
            return modelAndView;
            
        }
    }
    
    /**
     * 输入成绩
     * @param projectPhaseId
     * @param page
     * @return
     */
    @RequestMapping(value = "/{projectPhaseId}/trainee-score", method = RequestMethod.GET)
    public ModelAndView inputResult(@PathVariable("projectPhaseId") Long projectPhaseId, Page page) {
        ModelAndView modelAndView = new ModelAndView("project-result/project-result-score-edit");
        
        modelAndView.addObject("projectPhaseId", projectPhaseId);
        
        ProjectPhase projectPhase = projectPhaseService.load(ProjectPhase.class, projectPhaseId);
        modelAndView.addObject("projectPhase", projectPhase);
        modelAndView.addObject("project", projectPhase.getProject());
        
        return modelAndView;
    }
    
    /**
     * 培训结果提交
     * 
     * @return
     */
    @RequestMapping(value = "/{projectPhaseId}/trainee-score", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public HttpResult onInputResult(@PathVariable("projectPhaseId") Long projectPhaseId,
                                    @RequestParam(value = "userId") Long userId,
                                    ProjectTrainee projectTrainee) {

        HttpResult httpResult = new HttpResult();
        try {
            Trainee trainee = traineeService.load(Trainee.class, userId);
            projectTraineeService.editProjectTrainee(projectTrainee, trainee, projectPhaseId);
            httpResult.success().message("项目结果录入成功");

        } catch (Exception e) {
            httpResult.fail("500").message("项目结果录入失败! " + e.getMessage());
            logger.error("#onInputResult() - create project fail, exception is [{}]", e);
        }

        return httpResult;

    }
    

    /**
               * 成绩导出
     * @return
     */
    @RequestMapping(value = "/{projectId}/trainee-score-export")
    public ModelAndView export(@PathVariable("projectId") Long projectId) {
    	ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("project-trainee-score-export.xls"));
    	
    	 List<ProjectTrainee> projectTrainees = projectTraineeService.listByProjectId(projectId);
        		
         modelAndView.addObject("projectTrainees", projectTrainees);
    	
        return modelAndView;
    }
    
	
    /**
     * 项目详情
     * @param id
     * @param currentPhase
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @MenuSetting("submenu-project-result-management")
    public ModelAndView view(@PathVariable("id") Long id,
                             @RequestParam(name = "currentPhase", defaultValue="1") int currentPhase,
                             Page page, HttpServletRequest request) {
        
        ModelAndView modelAndView = new ModelAndView("project-result/project-result-view");
        
        Project project = projectDataService.load(Project.class, id);
        modelAndView.addObject("project", project);
        
        modelAndView.addObject("currentPhase", currentPhase);
        
        List<ProjectPhase> projectPhases = projectPhaseService.listByProject(project);
        modelAndView.addObject("projectPhases", projectPhases);
        modelAndView.addObject("projectPhase", projectPhases.get(currentPhase-1));
        modelAndView.addObject("size", projectPhases.size());
        
        List<ProjectPhaseCourse> projectPhaseCourses = projectPhaseCourseService.listByProjectPhase(projectPhases.get(currentPhase-1));
        modelAndView.addObject("projectPhaseCourses", projectPhaseCourses);
        
        if (currentPhase == projectPhases.size()) {
            int totals = projectTraineeService.countByProject(projectPhases.get(projectPhases.size()-1).getProject());
            if (totals > 0) {
                List<ProjectTrainee> projectTrainees = projectTraineeService.listByProject(projectPhases.get(projectPhases.size()-1).getProject(), page.with(totals));
                modelAndView.addObject("trainingResults", projectTrainees);
            }
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "filter", "page"));
            
        }else {
            int totals = trainingResultService.count(projectPhases.get(currentPhase-1));
            if (totals > 0) {
                List<TrainingResult> trainingResults = trainingResultService.listByProjectPhase(projectPhases.get(currentPhase-1), page.with(totals));
                modelAndView.addObject("trainingResults", trainingResults);
            }
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "filter", "page"));
            
        }
        return modelAndView;
    }

}
